<?php
/**
 * Copyright (C) "Code Generator Tools"
 * @author liya(358103599@qq.com)
 */

require_once 'DB.php';
require_once 'GenHelp.php';

/**
 * CI视图生成类
 */
class CIViewGen
{
	private $tables;
	private $savePath;
	private $iOutPut;

	public function __construct($tables, $saveBase, $iOutPut)
	{
		$this->tables = $tables;
		$this->savePath = $saveBase.'views/admin/';
		$this->iOutPut = $iOutPut;

		if(!file_exists($this->savePath))
		{
			mkdir($this->savePath, 0777, true);
		}
	}

	public function Gen()
	{
		if(empty($this->tables))
		{
			$this->iOutPut->WriteLine('No Tables');
			return;
		}

		$this->iOutPut->WriteHeader('Views('.count($this->tables).')');

		foreach($this->tables as $table)
		{
			$tablename = $table['TABLE_NAME'];
			$filedir = $this->savePath.strtolower($tablename).'/';
			$this->GenView($tablename, $filedir);			
		}
	}

	private function GenView($tablename, $filedir)
	{
		if(!file_exists($filedir))
		{
			mkdir($filedir, 0777, true);
		}

		$this->iOutPut->WriteLine("-- $tablename --");
		
		//生成 list.php
		$list_filename = $filedir.'list.php';
		$result = $this->GenViewList($tablename, $list_filename);
		$gen_state_str = ($result)?'OK':'Fail';
		$file_save_datetime = GenHelp::ZhDate();
		$this->iOutPut->WriteLine("generator ".$gen_state_str." $list_filename (".filesize($list_filename)." Byte) -- $file_save_datetime");

		//生成 form.php
		$form_filename = $filedir.'form.php';
		$result = $this->GenViewForm($tablename, $form_filename);
		$gen_state_str = ($result)?'OK':'Fail';
		$file_save_datetime = GenHelp::ZhDate();
		$this->iOutPut->WriteLine("generator ".$gen_state_str." $form_filename (".filesize($form_filename)." Byte) -- $file_save_datetime");

		//生成 detail.php
		$detail_filename = $filedir.'detail.php';
		$result = $this->GenViewDetail($tablename, $detail_filename);
		$gen_state_str = ($result)?'OK':'Fail';
		$file_save_datetime = GenHelp::ZhDate();
		$this->iOutPut->WriteLine("generator ".$gen_state_str." $detail_filename (".filesize($detail_filename)." Byte) -- $file_save_datetime");

		$this->iOutPut->WriteLine('');
	}

	private function GenViewList($tablename, $filename)
	{
		$db = new DB();

		$classname = ucfirst(strtolower($tablename));		
		$columns = $db->GetTableColumns($tablename);

		//读取模板文件到字符串变量 $model_str 中
		$model_template_file = dirname(__FILE__).'/codeigniter/_Template/view/list.php';
		$model_str = file_get_contents($model_template_file);

		/*
		 * 替换模板文件中的标记
		 * 
		 * {_datetime_}
		 * {_classname_}
		 * {_tablename_}
		 * {_tr_header_}
		 * {_tr_item_}
		 *
		 */
		$model_new_str = $model_str;
		$model_new_str = str_replace('{_datetime_}', GenHelp::ZhDate(), $model_new_str);
		$model_new_str = str_replace('{_classname_}', $classname, $model_new_str);
		$model_new_str = str_replace('{_tablename_}', $tablename, $model_new_str);

		//替换 {_tr_header_}
		$tr_header_str = $this->CreateViewListTableTrHeader($columns);
		$model_new_str = str_replace('{_tr_header_}', $tr_header_str, $model_new_str);

		//替换 {_tr_item_}
		$tr_item_str = $this->CreateViewListTableTr($tablename, $columns);
		$model_new_str = str_replace('{_tr_item_}', $tr_item_str, $model_new_str);

		//保存替换后的字符串到文件 $filename
		return file_put_contents($filename, $model_new_str);
	}

	//创建列表页中表格的表头模板
	private function CreateViewListTableTrHeader($columns)
	{
		$result = '<tr class="tr_header">'."\r\n";
		foreach($columns as $column)
		{
			$result .= "<td>{$column['COLUMN_NAME']}</td>\r\n";
		}
		$result .= '<td>查看详细</td>'."\r\n";
		$result .= '<td>编辑</td>'."\r\n";
		$result .= '<td>删除</td>'."\r\n";
		$result .= "</tr>\r\n";
		return $result;
	}

	//创建列表页中表格的记录行模板
	private function CreateViewListTableTr($tablename, $columns)
	{
		$result = '<tr class="tr_item">'."\r\n";
		//生成数据表列
		foreach($columns as $column)
		{
			$result .= '<td><?php echo empty($item->'.$column['COLUMN_NAME'].')? '."''".': $item->'.$column['COLUMN_NAME'].'; ?></td>'."\r\n";
		}
		//生成操作列
		$a_url_primary_key_value = $this->CreatePrimaryKeyValueUrlByViewList($columns);
		$a_detail_url = '<?php echo config_item("base_url"); ?>admin/'.strtolower($tablename).'/detail/'.$a_url_primary_key_value;
		$a_edit_url = '<?php echo config_item("base_url"); ?>admin/'.strtolower($tablename).'/edit/'.$a_url_primary_key_value;
		$a_delete_url = '<?php echo config_item("base_url"); ?>admin/'.strtolower($tablename).'/delete/'.$a_url_primary_key_value;
		
		$result .=	"<td><a href=\"$a_detail_url\" target=\"_blank\">查看详细</a></td>\r\n";
		$result .=	"<td><a href=\"$a_edit_url\" target=\"_blank\">编辑</a></td>\r\n";
		$result .=	"<td><a href=\"$a_delete_url\" target=\"_blank\">删除</a></td>\r\n";
		$result .= "</tr>\r\n";
		return $result;
	}

	//根据主键值生成 详细、编辑、删除页面的URL的内容，如以下的{0}中的值 detail/{0}、edit/{0}、delete/{0}
	private function CreatePrimaryKeyValueUrlByViewList($columns)
	{
		$result;
		$primary_columns = GenHelp::GetPrimaryKeyColumns($columns);
		foreach($primary_columns as $column)
		{
			$result .= '<?php echo empty($item->'.$column['COLUMN_NAME'].")? ''".': $item->'.$column['COLUMN_NAME'].'; ?>/';
		}
		$result = substr($result, 0, strlen($result) - 1);
		return $result;
	}

	private function GenViewForm($tablename, $filename)
	{
		$db = new DB();

		$classname = ucfirst(strtolower($tablename));		
		$columns = $db->GetTableColumns($tablename);

		//读取模板文件到字符串变量 $model_str 中
		$model_template_file = dirname(__FILE__).'/codeigniter/_Template/view/form.php';
		$model_str = file_get_contents($model_template_file);

		/*
		 * 替换模板文件中的标记
		 * 
		 * {_datetime_}
		 * {_classname_}
		 * {_tablename_}
		 *
		 */
		$model_new_str = $model_str;
		$model_new_str = str_replace('{_datetime_}', GenHelp::ZhDate(), $model_new_str);
		$model_new_str = str_replace('{_classname_}', ucfirst($tablename), $model_new_str);
		$model_new_str = str_replace('{_tablename_}', $tablename, $model_new_str);

		//保存替换后的字符串到文件 $filename
		return file_put_contents($filename, $model_new_str);
	}

	private function GenViewDetail($tablename, $filename)
	{
		$db = new DB();

		$classname = ucfirst(strtolower($tablename));		
		$columns = $db->GetTableColumns($tablename);

		//读取模板文件到字符串变量 $model_str 中
		$model_template_file = dirname(__FILE__).'/codeigniter/_Template/view/detail.php';
		$model_str = file_get_contents($model_template_file);

		/*
		 * 替换模板文件中的标记
		 * 
		 * {_datetime_}
		 * {_classname_}
		 * {_tablename_}
		 * {_tr_item_}
		 * {_controller_name_}
		 * {_primary_key_url_}
		 *
		 */
		$model_new_str = $model_str;
		$model_new_str = str_replace('{_datetime_}', GenHelp::ZhDate(), $model_new_str);
		$model_new_str = str_replace('{_classname_}', $classname, $model_new_str);
		$model_new_str = str_replace('{_tablename_}', $tablename, $model_new_str);

		//替换 {_tr_item_}
		$tr_item_str = $this->CreateViewDetailTableTr($tablename, $columns);
		$model_new_str = str_replace('{_tr_item_}', $tr_item_str, $model_new_str);

		//替换 {_controller_name_}
		$model_new_str = str_replace('{_controller_name_}', strtolower($tablename), $model_new_str);

		//替换 {_primary_key_url_}
		$primary_key_url_str = $this->CreatePrimaryKeyValueUrlByViewDetail($columns);
		$model_new_str = str_replace('{_primary_key_url_}', $primary_key_url_str, $model_new_str);

		//保存替换后的字符串到文件 $filename
		return file_put_contents($filename, $model_new_str);
	}

	//创建列表页中表格的记录行模板
	private function CreateViewDetailTableTr($tablename, $columns)
	{
		$result;
		foreach($columns as $column)
		{
			$cname = $column['COLUMN_NAME'];

			$result .= '<tr>'."\r\n";
			$result .= '<td class="td1">'.$cname.'</td>';
			$result .= '<td><?php echo empty($detail->'.$cname.')? '."''".': $detail->'.$cname.'; ?></td>'."\r\n";
			$result .= "</tr>\r\n";
		}
		return $result;
	}

	//根据主键值生成 详细、编辑、删除页面的URL的内容，如以下的{0}中的值 detail/{0}、edit/{0}、delete/{0}
	private function CreatePrimaryKeyValueUrlByViewDetail($columns)
	{
		$result;
		$primary_columns = GenHelp::GetPrimaryKeyColumns($columns);
		foreach($primary_columns as $column)
		{
			$result .= '<?php echo empty($detail->'.$column['COLUMN_NAME'].")? ''".': $detail->'.$column['COLUMN_NAME'].'; ?>/';
		}
		$result = substr($result, 0, strlen($result) - 1);
		return $result;
	}
}

?>